package com.dhh.sky.activity;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Stack;
import net.londatiga.android.ActionItem;
import net.londatiga.android.QuickAction;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import yuku.iconcontextmenu.IconContextMenu;
import yuku.iconcontextmenu.IconContextMenu.IconContextItemSelectedListener;
import com.dhh.sky.R;
import com.dhh.sky.SDAApplication;
import com.dhh.sky.dao.DataBaseHelper;
import com.dhh.sky.model.SkyDriveAlbum;
import com.dhh.sky.model.SkyDriveAudio;
import com.dhh.sky.model.SkyDriveFile;
import com.dhh.sky.model.SkyDriveFolder;
import com.dhh.sky.model.SkyDriveObject;
import com.dhh.sky.model.SkyDrivePhoto;
import com.dhh.sky.model.SkyDrivePhoto.Image;
import com.dhh.sky.model.SkyDriveVideo;
import com.dhh.sky.util.CopyAndPaste;
import com.dhh.sky.util.FileManager;
import com.dhh.sky.util.FilePicker;
import com.dhh.sky.util.FileUtil;
import com.dhh.sky.util.JsonKeys;
import com.dhh.sky.widget.AmazingAdapter;
import com.flurry.android.FlurryAgent;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.korovyansk.android.slideout.SlideoutActivity;
import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;
import com.microsoft.live.LiveAuthClient;
import com.microsoft.live.LiveAuthException;
import com.microsoft.live.LiveAuthListener;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveConnectSession;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveOperationException;
import com.microsoft.live.LiveOperationListener;
import com.microsoft.live.LiveStatus;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Pair;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint({ "HandlerLeak", "HandlerLeak" })
public class FileListActivity extends Activity implements View.OnClickListener{
	public static int RLT_FILE_PICK = 0;
	public static int RLT_GRID_VIEW = 1;
	public static int RLT_BATCH_PICK = 2;
	public final static String FILTER_DOCUMENT = "document";
	public final static String FILTER_PHOTOS = "photos";
	private final String CP_OP_COPY = "COPY";
	private final String CP_OP_MOVE = "MOVE";
    private Stack<String> mPrevFolderIds = new Stack<String>();
    private Stack<String> mPrevFolderNames = new Stack<String>();
	private ListView lsComposer;
	private LinearLayout upLst;
	private PullToRefreshListView plist;
	private SectionComposerAdapter adapter;	
    private String mCurrentFolderId;
    private String mCurrentFolderName;
    private LiveConnectClient mClient;
    private LiveAuthClient mAuthClient;
    private String HOME_FOLDER = "me/skydrive";
    private ActionBar actionBar;
    private FileManager fManager;
	private DataBaseHelper db;
	private Resources res;
    private List<SkyDriveObject> files = new ArrayList<SkyDriveObject>();
    private DisplayImageOptions options;
    private DisplayImageOptions dgOptions;
	private ImageLoader imageLoader = ImageLoader.getInstance();
    private String[] downloadFiles;
    private String filter;
    private final int OP_DOWNLOAD = 1;
    private final int OP_DELETE = 5;
    private final int OP_SHARE = 7;
    private final int OP_MORE = 8;
    private final int OP_PASTE = 9;
    private PasteAction pasteAction;
    private GridAction gridAction;
    private MoreAction moreAction;
    private UploadAction uploadAction;
    private DataUpdateReceiver dataUpdateReceiver;
    private SyncReceiver syncReceiver;
	private SharedPreferences sp;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.file_list); 
		mClient = ((SDAApplication) getApplication()).getConnectClient();
		mAuthClient = ((SDAApplication) getApplication()).getAuthClient();
        db = new DataBaseHelper(getBaseContext());
        db.openDataBase();        
		fManager = new FileManager(db);
		res = this.getResources();
		sp = getSharedPreferences("sync_file", 0);
		imageLoader.init(ImageLoaderConfiguration.createDefault(this));
		options = new DisplayImageOptions.Builder()
					.showStubImage(R.drawable.stub_image)
					.showImageForEmptyUrl(R.drawable.image_for_empty_url)
					.cacheInMemory()
					.cacheOnDisc()
					.build();
		dgOptions = new DisplayImageOptions.Builder()
					.showStubImage(R.drawable.img_load)
					.showImageForEmptyUrl(R.drawable.image_for_empty_url)
					.cacheInMemory()
					.cacheOnDisc()
					.build();
        
		dataUpdateReceiver = new DataUpdateReceiver();
		IntentFilter intentFilter = new IntentFilter("download");
		registerReceiver(dataUpdateReceiver, intentFilter);
		
		syncReceiver = new SyncReceiver();
		IntentFilter syncFilter = new IntentFilter("syncService");
		registerReceiver(syncReceiver, syncFilter);
		
		if(getIntent().getExtras()!=null){
			filter = getIntent().getExtras().getString("filter");
		}
		
        initView();
        initActionBar();
		new LoadFolderTask().execute(new String[]{});
	}
	
	@Override
	public void onStart(){
		super.onStart();
		FlurryAgent.onStartSession(this, "DECGTPUNA57HJIDJ41AW");
		mClient = ((SDAApplication) getApplication()).getConnectClient();
	}
	
	@Override
	public void onResume(){
		super.onResume();
	}
	
	public void onStop() {
		super.onStop();
		FlurryAgent.onEndSession(this);
	}
	
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mPrevFolderIds.isEmpty()) {
            	showDialog(0);
                return true;
            }
            
            mCurrentFolderId = mPrevFolderIds.pop();
            mCurrentFolderName = mPrevFolderNames.pop();
            loadFolder();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(RLT_FILE_PICK == resultCode){
			if(data==null)
				return;
			
			String[] files = data.getStringArrayExtra("files");
			String[] names = data.getStringArrayExtra("names");
			if(files.length>1){
				Intent intent = new Intent(this, BatchUploadService.class);
				intent.putExtra("path", mCurrentFolderId);
				intent.putExtra("names", names);
				intent.putExtra("files", files);
				startService(intent);
			}else{
				String file = files[0];
				String name = names[0];
				Intent intent = new Intent(this, DownloadService.class);
				intent.putExtra("mCurrentFolderId", mCurrentFolderId);
				intent.putExtra("filePath", file);
				intent.putExtra("name", name);
				intent.putExtra("operation", DownloadService.OP_UPLOAD);
				startService(intent);
			}
			
			this.showToast(res.getString(R.string.upload_start));
		}else if(RLT_GRID_VIEW == resultCode){
			
		}
	}
	
	@Override
	public void onClick(View view) {
		
	}
	
	@Override
    protected Dialog onCreateDialog(final int id) {
        Dialog dialog = null;
        switch (id) {
            case 0: {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(res.getString(R.string.menu_logout))
                       .setMessage(res.getString(R.string.msg_logout))
                       .setPositiveButton(res.getString(R.string.ok), new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    	pHandler.sendEmptyMessage(0);
                        mAuthClient.logout(new LiveAuthListener() {
                            @Override
                            public void onAuthError(LiveAuthException exception, Object userState) {
                            	pHandler.sendEmptyMessage(1);
                                showToast(exception.getMessage());
                            }

                            @Override
                            public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
                                SDAApplication app = (SDAApplication)getApplication();
                                app.setSession(null);
                                app.setConnectClient(null);
                                pHandler.sendEmptyMessage(1);
                                Intent intent = new Intent(FileListActivity.this,SDAActivity.class);
                                startActivity(intent);
                            }
                        });
                    }
                }).setNegativeButton(res.getString(R.string.cancel), new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

                dialog = builder.create();
                break;
            }
        }

        if (dialog != null) {
            dialog.setOnDismissListener(new OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    removeDialog(id);
                }
            });
        }

        return dialog;
    }
	
	private void initActionBar(){
		pasteAction = new PasteAction();
		moreAction = new MoreAction();
		uploadAction = new UploadAction();
		gridAction = new GridAction();
		actionBar = (ActionBar) findViewById(R.id.actionbar);
		actionBar.setTitle(this.getString(R.string.home_title));
		actionBar.setHomeAction(new HomeAction());
		
		actionBar.addAction(uploadAction);
		actionBar.addAction(moreAction);
	}
	
	
	private class GridAction implements Action {
	    @Override
	    public int getDrawable() {
	        return R.drawable.ic_grid_img_2;
	    }

	    @Override
	    public void performAction(View view) {
	    	Intent intent = new Intent(getApplicationContext(), ImageGridActivity.class);
	    	List<String[]> all = getImgUrls();
	    	String[] imgs = all.get(0);
	    	String[] ids = all.get(1);
	    	String[] names = all.get(2);
	    	String[] imgsNormal = all.get(3);
	    	intent.putExtra("imgs", imgs);
	    	intent.putExtra("ids", ids);
	    	intent.putExtra("names", names);
	    	intent.putExtra("imgsNormal", imgsNormal);
	    	FileListActivity.this.startActivityForResult(intent, 0);
	    }

	}
	
	private class MoreAction implements Action {
	    @Override
	    public int getDrawable() {
	        return R.drawable.ic_list;
	    }

	    @Override
	    public void performAction(View view) {
			IconContextMenu cm = new IconContextMenu(FileListActivity.this, R.menu.more_menu);
			if(!CopyAndPaste.canPlate() || isCurrentFolder(CopyAndPaste.getPath())){
				cm.getMenu().removeItem(R.id.menu_paste);
			}
			cm.setOnIconContextItemSelectedListener(new IconContextItemSelectedListener(){
				@Override
				public void onIconContextItemSelected(MenuItem item, Object info) {
					if(item.getItemId()==R.id.menu_new_folder){
						getAlertDialogNewFolder(mCurrentFolderId).show();
					}else if(item.getItemId()==R.id.menu_refresh){
						loadFolderNoLoading();
					}else if(item.getItemId()==R.id.menu_paste){
						if(CP_OP_COPY.equals(CopyAndPaste.operation)){
							copyFile(CopyAndPaste.plate(),mCurrentFolderId);
						}else if(CP_OP_MOVE.equals(CopyAndPaste.operation)){
							moveFile(CopyAndPaste.plate(),mCurrentFolderId);
						}
						
						CopyAndPaste.operation = "";						
					}		
				}});
			cm.show();
	    }
	}
	
	private boolean isCurrentFolder(String path){
    	for(SkyDriveObject obj : files){
    		if(obj.getId().equalsIgnoreCase(path)){
    			return true;
    		}
    	}	    	
    	
    	return false;
    }
	
	private class HomeAction implements Action {
	    @Override
	    public int getDrawable() {
	        return R.drawable.ic_home_arrow;
	    }

	    @Override
	    public void performAction(View view) {	    	
	    	int width = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 40, getResources().getDisplayMetrics());
			SlideoutActivity.prepare(FileListActivity.this, R.id.inner_content, width);
			startActivity(new Intent(FileListActivity.this,MenuActivity.class));
			overridePendingTransition(0, 0);
	    }

	}
	
	private class PasteAction implements Action {
	    @Override
	    public int getDrawable() {
	        return R.drawable.ic_paste;
	    }

	    @Override
	    public void performAction(View view) {	    	
	    	if(CP_OP_COPY.equals(CopyAndPaste.operation)){
				copyFile(CopyAndPaste.plate(),mCurrentFolderId);
			}else if(CP_OP_MOVE.equals(CopyAndPaste.operation)){
				moveFile(CopyAndPaste.plate(),mCurrentFolderId);
			}			
			CopyAndPaste.operation = "";
	    }

	}
	
	private class UploadAction implements Action {
	    @Override
	    public int getDrawable() {
	        return R.drawable.ic_upload;
	    }

	    @Override
	    public void performAction(View view) {
	    	Intent intent = new Intent(getApplicationContext(), FilePicker.class);
	    	FileListActivity.this.startActivityForResult(intent, FilePicker.PICK_FILE_REQUEST);
	    }

	}
	
	private void showContextMenu(final int position){				
		final SkyDriveObject file = (SkyDriveObject) lsComposer.getAdapter().getItem(position);				
		IconContextMenu cm = new IconContextMenu(FileListActivity.this, R.menu.context_menu);		
		if(file.getType().equals(SkyDriveFolder.TYPE) || file.getType().equals(SkyDriveAlbum.TYPE)){
			cm.getMenu().removeItem(R.id.menu_download);
			cm.getMenu().removeItem(R.id.menu_copy);
			if(!CopyAndPaste.canPlate()){
				cm.getMenu().removeItem(R.id.menu_paste);
			}
			
			if(CopyAndPaste.getParent()!=null && CopyAndPaste.getParent().equals(file.getId())){
				cm.getMenu().removeItem(R.id.menu_paste);
			}
		}else{
			cm.getMenu().removeItem(R.id.menu_paste);
		}
		cm.setOnIconContextItemSelectedListener(new IconContextItemSelectedListener(){
			@Override
			public void onIconContextItemSelected(MenuItem item,Object info) {
				if(item.getItemId() == R.id.menu_delete){
					pHandler.sendEmptyMessage(0);
					delConfirm(file.getId());
				}else if(item.getItemId() == R.id.menu_download){
					Intent intent = new Intent(FileListActivity.this, DownloadService.class);
					intent.putExtra("operation", DownloadService.OP_DOWNLOAD);
					String source = "";
					if (file.getType().equals(SkyDriveFile.TYPE)) {
						source = ((SkyDriveFile) file).getSource();
					} else if (file.getType().equals(SkyDrivePhoto.TYPE)) {
						source = ((SkyDrivePhoto) file).getSource();
					} else if (file.getType().equals(SkyDriveVideo.TYPE)) {
						source = ((SkyDriveVideo) file).getSource();
					} else if (file.getType().equals(SkyDriveAudio.TYPE)) {
						source = ((SkyDriveAudio) file).getSource();
					}
					intent.putExtra("source", source);
					intent.putExtra("name", file.getName());
					startService(intent);
					
					FileListActivity.this.showToast(res.getString(R.string.download_start));
				}else if(item.getItemId() == R.id.menu_rename){
					getAlertDialogTextEdit("",file.getName(),file.getId()).show();
				}else if(item.getItemId() == R.id.menu_share){
					shareFile(file.getId());
				}else if(item.getItemId() == R.id.menu_copy){
					CopyAndPaste.copy(file.getId(),file.getParentId());
					CopyAndPaste.operation =  CP_OP_COPY;
				}else if(item.getItemId() == R.id.menu_cut){
					CopyAndPaste.copy(file.getId(),file.getParentId());
					CopyAndPaste.operation =  CP_OP_MOVE;
				}else if(item.getItemId() == R.id.menu_paste){
					if(CP_OP_COPY.equals(CopyAndPaste.operation)){
						copyFile(CopyAndPaste.plate(),file.getId());
					}else if(CP_OP_MOVE.equals(CopyAndPaste.operation)){								
						moveFile(CopyAndPaste.plate(),file.getId());
					}
					
					CopyAndPaste.operation = "";
				}
			}});
		cm.show();
	}
	
	private void initView(){		
		upLst = (LinearLayout) findViewById(R.id.fl_up_lst);
		upLst.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				if (!mPrevFolderIds.isEmpty()) {
					mCurrentFolderId = mPrevFolderIds.pop();
		            mCurrentFolderName = mPrevFolderNames.pop();
		            loadFolder(); 
	            }
			}
		});
		
		plist = (PullToRefreshListView) findViewById(R.id.flComposer);
		lsComposer = plist.getRefreshableView();   
        lsComposer.setTextFilterEnabled(true);
		lsComposer.setDivider( null );
		lsComposer.setDividerHeight(1); 
		lsComposer.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {				
				showContextMenu(position);
				return true;
			}
		}); 
		
		lsComposer.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
				final SkyDriveObject item = (SkyDriveObject) lsComposer.getAdapter().getItem(position);
				if(item.getType().equals(SkyDriveFolder.TYPE) || item.getType().equals(SkyDriveAlbum.TYPE)){
					mPrevFolderIds.push(mCurrentFolderId);
					mPrevFolderNames.push(mCurrentFolderName);
					mCurrentFolderName = item.getName();
					mCurrentFolderId = item.getId();
					loadFolder();
				}else{
					String director = Environment.getExternalStorageDirectory().getPath();
			        final File file = new File(director+"/SkyDrive/"+item.getName());
			        
					if (item.getType().equals(SkyDrivePhoto.TYPE)){						
						SkyDrivePhoto photo = ((SkyDrivePhoto) item);
						ImageDialog imgDialog = new ImageDialog(FileListActivity.this,R.style.dialog,photo,file);
						imgDialog.show();
					}else{
						LayoutInflater inflater 	= (LayoutInflater) FileListActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
						final Dialog dialog = new Dialog(FileListActivity.this);
						dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
						View container	= (View) inflater.inflate(R.layout.file_detail, null);
						TextView name = (TextView) container.findViewById(R.id.fd_name_t);
						TextView desc = (TextView) container.findViewById(R.id.fd_update_by_t);
						TextView date = (TextView) container.findViewById(R.id.fd_modify_time_t);
						TextView size = (TextView) container.findViewById(R.id.fd_size_t);
						Button pButton = (Button) container.findViewById(R.id.fd_button_p);
						Button dButton = (Button) container.findViewById(R.id.fd_button_d);
						Button nButton = (Button) container.findViewById(R.id.fd_button_n);
						name.setText(item.getName());
						date.setText(getFileModifyDate(item.getUpdatedTime()));
						long sVal = 0;
						if (item.getType().equals(SkyDriveFile.TYPE)) {
							sVal = ((SkyDriveFile) item).getSize();
						} else if (item.getType().equals(SkyDrivePhoto.TYPE)) {
							sVal = ((SkyDrivePhoto) item).getSize();
						} else if (item.getType().equals(SkyDriveVideo.TYPE)) {
							sVal = ((SkyDriveVideo) item).getSize();
						} else if (item.getType().equals(SkyDriveAudio.TYPE)) {
							sVal = ((SkyDriveAudio) item).getSize();
						}
						String fSize = "";
						DecimalFormat numFormat = new DecimalFormat("###,###");
						if(sVal>0 && sVal/1024>1){
							fSize = numFormat.format(sVal/1024) + " KB ";
							if(sVal/1024/1024>1){
								DecimalFormat nf = new DecimalFormat(".#");
								fSize = nf.format(sVal/1024/1024.0) + " MB ";
							}
							size.setText(fSize);
						}else if(sVal>0){
							fSize = "1 KB ";
							size.setText(fSize);
						}else if(item.getType().equals(SkyDriveFolder.TYPE)){
							size.setText("");
						}else if(item.getType().equals(SkyDriveAlbum.TYPE)){
							size.setText("");
						} 
						desc.setText(item.getSharedWith().getAccess());				        
				        
				        if(file.exists()){
				        	dButton.setVisibility(View.GONE);
				        	pButton.setOnClickListener(new View.OnClickListener(){
								@Override
								public void onClick(View v) {
									Intent intent = new Intent();
			                        intent.setAction(android.content.Intent.ACTION_VIEW);                   
			                        MimeTypeMap mime = MimeTypeMap.getSingleton();
			                        String ext=FileUtil.getFileExt(file.getName());
			                        if(ext!=null)
			                        	ext = ext.toLowerCase();
			                        String type = mime.getMimeTypeFromExtension(ext);                  
			                        intent.setDataAndType(Uri.fromFile(file),type);                   
			                        startActivity(intent);

						        	dialog.dismiss();
								}});
				        }else{
				        	dButton.setVisibility(View.VISIBLE);
				        	pButton.setOnClickListener(new View.OnClickListener(){
								@Override
								public void onClick(View v) {
									Intent intent = new Intent(FileListActivity.this, DownloadMessageService.class);
									String source = "";
									if (item.getType().equals(SkyDriveFile.TYPE)) {
										source = ((SkyDriveFile) item).getSource();
									} else if (item.getType().equals(SkyDrivePhoto.TYPE)) {
										source = ((SkyDrivePhoto) item).getSource();
									} else if (item.getType().equals(SkyDriveVideo.TYPE)) {
										source = ((SkyDriveVideo) item).getSource();
									} else if (item.getType().equals(SkyDriveAudio.TYPE)) {
										source = ((SkyDriveAudio) item).getSource();
									}
									intent.putExtra("source", source);
									intent.putExtra("name", file.getName());
									intent.putExtra("id", item.getId());
									startService(intent);
									
									dialog.dismiss();
									
//									Intent it = new Intent(FileListActivity.this,VideoViewDemo.class);
//									it.putExtra("source", source);
//									startActivity(it);
									
								}});
				        }
				        
				        dButton.setOnClickListener(new View.OnClickListener() {						
							@Override
							public void onClick(View v) {
								Intent intent = new Intent(FileListActivity.this, DownloadService.class);
								intent.putExtra("operation", DownloadService.OP_DOWNLOAD);
								String source = "";
								if (item.getType().equals(SkyDriveFile.TYPE)) {
									source = ((SkyDriveFile) item).getSource();
								} else if (item.getType().equals(SkyDrivePhoto.TYPE)) {
									source = ((SkyDrivePhoto) item).getSource();
								} else if (item.getType().equals(SkyDriveVideo.TYPE)) {
									source = ((SkyDriveVideo) item).getSource();
								} else if (item.getType().equals(SkyDriveAudio.TYPE)) {
									source = ((SkyDriveAudio) item).getSource();
								}
								intent.putExtra("source", source);
								intent.putExtra("name", file.getName());
								startService(intent);
								showToast(res.getString(R.string.download_start));		

								dialog.dismiss();
							}
						});
						
						nButton.setOnClickListener(new View.OnClickListener() {						
							@Override
							public void onClick(View v) {
								dialog.dismiss();
							}
						});
						
						dialog.setContentView(container);
						dialog.setTitle(item.getName());						
						dialog.show();
					}
					
					
				}
			}
		});	
		
		plist.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				loadFolderNoLoading();
				plist.onRefreshComplete();
			}
		});
		lsComposer.setCacheColorHint(Color.WHITE);
	}
	
	private void initData(){
		adapter = new SectionComposerAdapter();
		List<Pair<String, List<SkyDriveObject>>> data = new ArrayList<Pair<String, List<SkyDriveObject>>>();
		if(!this.mCurrentFolderId.equalsIgnoreCase(this.HOME_FOLDER)){
			
		}
		Pair<String, List<SkyDriveObject>> pair = new Pair<String, List<SkyDriveObject>>("",files);
		data.add(pair);
		adapter.setData(data);
		
		if(files.size()==0){
			plist.setVisibility(View.GONE);
		}else{
			plist.setVisibility(View.VISIBLE);
			lsComposer.setAdapter(adapter);
		}
		adapter.notifyDataSetChanged();
		
	}
	
	private void refreshData(){
		List<SkyDriveObject> lst = fManager.getFiles(mCurrentFolderId);
    	// filter file by request
		filterFiles(lst,filter);
		files.clear();
		files.addAll(lst);
		
		if(files.size()==0){
			this.findViewById(R.id.fl_empty_lst).setVisibility(View.VISIBLE);
			this.findViewById(R.id.flComposer).setVisibility(View.GONE);
		}else{
			this.findViewById(R.id.fl_empty_lst).setVisibility(View.GONE);
			this.findViewById(R.id.flComposer).setVisibility(View.VISIBLE);
		}
		
		initData();
	}
	
	private void setActionTitle(){
		String title = res.getString(R.string.home_title);
		if(!HOME_FOLDER.equals(this.mCurrentFolderId)){
			title = mCurrentFolderName;
		}
		
		actionBar.setTitle(title);		
	}
	
	private boolean needSyn(SkyDriveObject obj){
		boolean flag = false;
		
		long start = Long.valueOf(obj.getMeta());
		long end = new Date().getTime();
		if((end-start)>(4*3600*1000)){
			flag = true;
		}
		
		return flag;
	}
	
	private Handler pHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        	if(msg.what==0){
        		actionBar.setProgressBarVisibility(View.VISIBLE);
        	}else{
        		actionBar.setProgressBarVisibility(View.GONE);
        	}
        }
    };
    
    private void checkAlbum(){
    	boolean isAlbum = false;
    	
    	if(!HOME_FOLDER.equalsIgnoreCase(mCurrentFolderId)){
    		SkyDriveObject cfile = fManager.getFile(mCurrentFolderId);
    		if(cfile.getType().equals(SkyDriveAlbum.TYPE)){
    			isAlbum = true;
    		}
    	}
    	
    	if(isAlbum)
    		actionBar.addAction(gridAction,1);
    	else
    		actionBar.removeAction(gridAction);
    }
	
	private void loadFolder(){
		try{
	    	actionHandler.sendEmptyMessage(0);
			downloadFiles = getDownlods();
			
			if(mCurrentFolderId ==null || mCurrentFolderId.trim().length()==0){
	        	mCurrentFolderId = HOME_FOLDER;        	
	        }			

			//initial 'Up To' item
			if(mCurrentFolderId==null || mCurrentFolderId.equalsIgnoreCase(HOME_FOLDER)){
				upLst.setVisibility(View.GONE);
			}else{
				TextView upText = (TextView) this.findViewById(R.id.fl_up_txt);
				upText.setText(this.getString(R.string.lab_up_to) +" "+ getParentName());
				upLst.setVisibility(View.VISIBLE);
			}
	        
	        setActionTitle();
	    	FileListActivity.this.findViewById(R.id.td_loading).setVisibility(View.VISIBLE);
	    	//if this is a album, then add grid action item.
	    	checkAlbum();
	    	List<SkyDriveObject> lst = fManager.getFiles(mCurrentFolderId);
	    	if(lst.size()>0){ 
	    		files.clear();
	    		files.addAll(lst);
	    		handler.sendEmptyMessage(0);
	    		if(needSyn(lst.get(0))){
	    			loadFolderNoLoading();
	    		}
	    		
	    	}else{
	    		String path = mCurrentFolderId + "/files";
	    		mClient.getAsync(path, new LiveOperationListener(){
		            @Override
		            public void onComplete(LiveOperation operation) {
		                JSONObject result = operation.getResult();
		                if (result.has(JsonKeys.ERROR)) {
		                    JSONObject error = result.optJSONObject(JsonKeys.ERROR);
		                    String message = error.optString(JsonKeys.MESSAGE);
		                    String code = error.optString(JsonKeys.CODE);
		                    showToast(code + ": " + message);
		                    return;
		                }
		                
		                files.clear();
		                JSONArray data = result.optJSONArray(JsonKeys.DATA);
		                for (int i = 0; i < data.length(); i++) {
		                    SkyDriveObject skyDriveObj = SkyDriveObject.create(data.optJSONObject(i));
		                    files.add(skyDriveObj);
		                }
		                fManager.update(files, mCurrentFolderId);
		                handler.sendEmptyMessage(0);
		            }

		            @Override
		            public void onError(LiveOperationException exception, LiveOperation operation) {
		                showToast(exception.getMessage());
		                FileListActivity.this.findViewById(R.id.td_loading).setVisibility(View.GONE);
		            }
		        });
	    	}    	
	        
		}catch(Exception e){
			e.printStackTrace();
			Intent intent = new Intent(this,SDAActivity.class);
			this.startActivity(intent);
		}
        
    }
	
	private void loadFolderNoLoading() {
        if(mCurrentFolderId ==null || mCurrentFolderId.trim().length()==0){
        	mCurrentFolderId = HOME_FOLDER;        	
        }
        
        pHandler.sendEmptyMessage(0);
        
        if(!isMyServiceRunning() && sp.getString("sync_"+mCurrentFolderId, null)!=null){
        	return;
        }
        
        String path = mCurrentFolderId + "/files";        
        Intent intent = new Intent(FileListActivity.this,SyncService.class);
		intent.putExtra("path", path);
		intent.putExtra("parent",mCurrentFolderId);
		startService(intent);
    }
	
	private boolean isMyServiceRunning() {
	    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
	    
	    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
	        if ("com.dhh.sky.activity.SyncService".equals(service.service.getClassName())) {
	            return true;
	        }
	    }
	    return false;
	}
	
	private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {    
        	if(!CopyAndPaste.canPlate() || isCurrentFolder(CopyAndPaste.getPath())){
				actionBar.removeAction(pasteAction);  
			}else{
				actionBar.removeAllActions();
				actionBar.addAction(uploadAction);
				actionBar.addAction(pasteAction);
				actionBar.addAction(moreAction);
			}
        	
        	refreshData();
        	FileListActivity.this.findViewById(R.id.td_loading).setVisibility(View.GONE);
        	actionBar.setProgressBarVisibility(View.GONE);
        }
    };
    
    private Handler actionHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {    
        	if(!CopyAndPaste.canPlate() || isCurrentFolder(CopyAndPaste.getPath())){
				actionBar.removeAction(pasteAction);  
			}else{
				actionBar.removeAllActions();
				actionBar.addAction(uploadAction);
				actionBar.addAction(pasteAction);
				actionBar.addAction(moreAction);
			}
        }
    };
	
	private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }
	
	class SectionComposerAdapter extends AmazingAdapter {
		List<Pair<String, List<SkyDriveObject>>> all = null;
		DecimalFormat numFormat = new DecimalFormat("###,###");
		
		public void setData(List<Pair<String, List<SkyDriveObject>>> data){
			all = data;
		}

		@Override
		public int getCount() {
			int res = 0;
			for (int i = 0; i < all.size(); i++) {
				res += all.get(i).second.size();
			}
			return res;
		}

		@Override
		public SkyDriveObject getItem(int position) {
			int c = 0;
			for(int i = 0; i < all.size(); i++) {
				if(position >= c && position < c + all.get(i).second.size()) {
					return all.get(i).second.get(position - c);
				}
				c += all.get(i).second.size();
			}
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		protected void onNextPageRequested(int page) {
		}

		@Override
		protected void bindSectionHeader(View view, int position, boolean displaySectionHeader) {
			view.findViewById(R.id.header).setVisibility(View.GONE);
		}

		@Override
		public View getAmazingView(final int position, View convertView, ViewGroup parent) {
			View res = convertView;
			if (res == null) res = getLayoutInflater().inflate(R.layout.file_list_item, null);
			final SkyDriveObject file = (SkyDriveObject) getItem(position);	
			Button icon = (Button) res.findViewById(R.id.fli_icon);
			TextView title = (TextView) res.findViewById(R.id.fli_title);
			TextView date = (TextView) res.findViewById(R.id.fli_date);
			TextView id = (TextView) res.findViewById(R.id.fli_id);
			TextView size = (TextView) res.findViewById(R.id.fli_size);
			final Button moreButton = (Button) res.findViewById(R.id.fli_more);	
			LinearLayout moreLst = (LinearLayout) res.findViewById(R.id.fli_more_lst);		
			
			if(!(file.getType().equalsIgnoreCase(SkyDriveFolder.TYPE) && file.getType().equalsIgnoreCase(SkyDriveAlbum.TYPE)) 
					&& isDownload(file.getName())){
				res.findViewById(R.id.fli_downloaded).setVisibility(View.VISIBLE);
			}else{
				res.findViewById(R.id.fli_downloaded).setVisibility(View.GONE);
			}
			
			View.OnClickListener listener = new View.OnClickListener() {				
				@Override
				public void onClick(View v) {
					QuickAction quickAction = new QuickAction(FileListActivity.this);	
					// Paste
					if(file.getType().equals(SkyDriveFolder.TYPE) || file.getType().equals(SkyDriveAlbum.TYPE)){
						if(CopyAndPaste.canPlate() && !(CopyAndPaste.getParent()!=null && CopyAndPaste.getParent().equals(file.getId()))){ 
							ActionItem pasteItem     = new ActionItem(OP_PASTE, FileListActivity.this.getString(R.string.quick_paste), getResources().getDrawable(R.drawable.ic_paste));
							quickAction.addActionItem(pasteItem);
						}
					}
					// Download
					if(!file.getType().equals(SkyDriveFolder.TYPE) && !file.getType().equals(SkyDriveAlbum.TYPE)){
						ActionItem downloadItem     = new ActionItem(OP_DOWNLOAD, FileListActivity.this.getString(R.string.quick_download), getResources().getDrawable(R.drawable.ic_download));
						quickAction.addActionItem(downloadItem);						
					}
					// Delete
					ActionItem deleteItem     = new ActionItem(OP_DELETE, FileListActivity.this.getString(R.string.quick_delete), getResources().getDrawable(R.drawable.ic_delete));
					quickAction.addActionItem(deleteItem);
					// Share
					ActionItem shareItem     = new ActionItem(OP_SHARE, FileListActivity.this.getString(R.string.quick_share), getResources().getDrawable(R.drawable.ic_share));
					quickAction.addActionItem(shareItem);	
					// More
					ActionItem moreItem     = new ActionItem(OP_MORE, FileListActivity.this.getString(R.string.quick_more), getResources().getDrawable(R.drawable.ic_plus));
					quickAction.addActionItem(moreItem);
					quickAction.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener(){
						@Override
						public void onItemClick(QuickAction sourceItem, int pos, int actionId) {
							if(actionId == OP_PASTE){
								if(CP_OP_COPY.equals(CopyAndPaste.operation)){
									copyFile(CopyAndPaste.plate(),file.getId());
								}else if(CP_OP_MOVE.equals(CopyAndPaste.operation)){								
									moveFile(CopyAndPaste.plate(),file.getId());
								}								
								CopyAndPaste.operation = "";
							}else if(actionId == OP_DOWNLOAD){
								Intent intent = new Intent(FileListActivity.this, DownloadService.class);
								intent.putExtra("operation", DownloadService.OP_DOWNLOAD);
								String source = "";
								if (file.getType().equals(SkyDriveFile.TYPE)) {
									source = ((SkyDriveFile) file).getSource();
								} else if (file.getType().equals(SkyDrivePhoto.TYPE)) {
									source = ((SkyDrivePhoto) file).getSource();
								} else if (file.getType().equals(SkyDriveVideo.TYPE)) {
									source = ((SkyDriveVideo) file).getSource();
								} else if (file.getType().equals(SkyDriveAudio.TYPE)) {
									source = ((SkyDriveAudio) file).getSource();
								}
								intent.putExtra("source", source);
								intent.putExtra("name", file.getName());
								startService(intent);
								
								FileListActivity.this.showToast(FileListActivity.this.getString(R.string.download_start));
							}else if(actionId == OP_DELETE){
								pHandler.sendEmptyMessage(0);
								delConfirm(file.getId());
							}else if(actionId == OP_SHARE){
								shareFile(file.getId());
							}else if(actionId == OP_MORE){
								showContextMenu(position+1);
							}
							
						}});
					quickAction.show(moreButton);
				}
			};
			

			moreLst.setOnClickListener(listener);
			moreButton.setOnClickListener(listener);
			
			SkyDriveObject item = getItem(position);
			
			//initial icon
			icon.setBackgroundResource(item.getDrawableRes());
			setFileIcon(icon,item.getName());		
			
			
			if(file.getType().equalsIgnoreCase(SkyDrivePhoto.TYPE)){
				icon.setVisibility(View.GONE);
				ImageView img = (ImageView) res.findViewById(R.id.fli_img);
				SkyDrivePhoto ph = (SkyDrivePhoto)file;
				String src = "";
				for(Image im : ph.getImages()){
					if(im.getType().equalsIgnoreCase("thumbnail")){
						src = im.getSource();
						break;
					}
				}
				imageLoader.displayImage(src, img, options);
				img.setVisibility(View.VISIBLE);
			}else{
				icon.setVisibility(View.VISIBLE);
				res.findViewById(R.id.fli_img).setVisibility(View.GONE);
			}
			title.setText(item.getName());
			date.setText(getFileModifyDate(item.getUpdatedTime()));			
			id.setText(item.getId());
			
			String fSize = "";
			long sVal = 0;
			if (item.getType().equals(SkyDriveFile.TYPE)) {
				sVal = ((SkyDriveFile) item).getSize();
			} else if (item.getType().equals(SkyDrivePhoto.TYPE)) {
				sVal = ((SkyDrivePhoto) item).getSize();
			} else if (item.getType().equals(SkyDriveVideo.TYPE)) {
				sVal = ((SkyDriveVideo) item).getSize();
			} else if (item.getType().equals(SkyDriveAudio.TYPE)) {
				sVal = ((SkyDriveAudio) item).getSize();
			}

			
			if(sVal>0 && sVal/1024>1){
				fSize = numFormat.format(sVal/1024) + " KB, ";
				if(sVal/1024/1024>1){
					DecimalFormat nf = new DecimalFormat(".#");
					fSize = nf.format(sVal/1024/1024.0) + " MB, ";
				}
				size.setText(fSize);
				size.setVisibility(View.VISIBLE);
			}else if(sVal>0){
				fSize = "1 KB, ";
				size.setText(fSize);
			}else if(sVal==0){
				size.setVisibility(View.GONE);
			}			
			
			return res;
		}

		@Override
		public void configurePinnedHeader(View header, int position, int alpha) {
			TextView lSectionHeader = (TextView)header;
			lSectionHeader.setText(getSections()[getSectionForPosition(position)]);
			lSectionHeader.setBackgroundColor(alpha << 24 | (0xbbffbb));
			lSectionHeader.setTextColor(alpha << 24 | (0x000000));
		}
		

		@Override
		public int getPositionForSection(int section) {
			if (section < 0) section = 0;
			if (section >= all.size()) section = all.size() - 1;
			int c = 0;
			for (int i = 0; i < all.size(); i++) {
				if (section == i) { 
					return c;
				}
				c += all.get(i).second.size();
			}
			return 0;
		}

		@Override
		public int getSectionForPosition(int position) {
			int c = 0;
			for (int i = 0; i < all.size(); i++) {
				if (position >= c && position < c + all.get(i).second.size()) {
					return i;
				}
				c += all.get(i).second.size();
			}
			return -1;
		}

		@Override
		public String[] getSections() {
			String[] res = new String[all.size()];
			for (int i = 0; i < all.size(); i++) {
				res[i] = all.get(i).first;
			}
			return res;
		}
		
	}
	
	private void removeFile(final String path){
		mClient.deleteAsync(path, new LiveOperationListener(){			
			@Override
			public void onComplete(LiveOperation operation) {
				fManager.delFile(path);	
				refreshData();
				pHandler.sendEmptyMessage(1);
			}

			@Override
			public void onError(LiveOperationException exception,LiveOperation operation) {
				pHandler.sendEmptyMessage(1);
				showToast(exception.getMessage());
				FileListActivity.this.loadFolder();
			}});
	}
	
	private void renameFile(final String path,final String name){
		JSONObject body = new JSONObject();
		try {
			body.put("name", name);
		} catch (JSONException e) {
		}
		mClient.putAsync(path, body, new LiveOperationListener(){
			@Override
			public void onComplete(LiveOperation operation) {
				JSONObject obj = operation.getResult();
				SkyDriveObject f = initObject(obj.toString(),String.valueOf(new Date().getTime()));
				fManager.delFile(path);
				fManager.addFile(f);
				refreshData();
				pHandler.sendEmptyMessage(1);
			}

			@Override
			public void onError(LiveOperationException exception,LiveOperation operation) {
				showToast(exception.getMessage());
				pHandler.sendEmptyMessage(1);
				FileListActivity.this.loadFolder();			
			}});
		
	}
	
	private void createFolder(final String path,final String name,final String description){
		pHandler.sendEmptyMessage(0);
		JSONObject body = new JSONObject();
		try {
			body.put("name", name);
			body.put("description", description);
		} catch (JSONException e) {
		}
		mClient.postAsync(path, body, new LiveOperationListener(){
			@Override
			public void onComplete(LiveOperation operation) {
				loadFolderNoLoading();
			}

			@Override
			public void onError(LiveOperationException exception,LiveOperation operation) {
				pHandler.sendEmptyMessage(1);
				showToast(exception.getMessage());
			}});
		
	}
	
	private void copyFile(final String path,final String dest){
		pHandler.sendEmptyMessage(0);
		actionHandler.sendEmptyMessage(0);
		mClient.copyAsync(path, dest, new LiveOperationListener(){

			@Override
			public void onComplete(LiveOperation operation) {
				JSONObject obj = operation.getResult();
				if(obj.has(JsonKeys.ERROR)){
        			showToast(FileListActivity.this.getString(R.string.error_fail_operation));
        			pHandler.sendEmptyMessage(1);
        			return;
        		}
				SkyDriveObject f = initObject(obj.toString(),String.valueOf(new Date().getTime()));
				fManager.addFile(f);
				refreshData();
				pHandler.sendEmptyMessage(1);
			}

			@Override
			public void onError(LiveOperationException exception,LiveOperation operation) {
				showToast(exception.getMessage());
				pHandler.sendEmptyMessage(1);
			}});		
	}
	
	private void moveFile(final String path,final String dest){
		pHandler.sendEmptyMessage(0);
		actionHandler.sendEmptyMessage(0);
		mClient.moveAsync(path, dest, new LiveOperationListener(){

			@Override
			public void onComplete(LiveOperation operation) {
				fManager.delFile(path);
				JSONObject obj = operation.getResult();
				SkyDriveObject f = initObject(obj.toString(),String.valueOf(new Date().getTime()));
				fManager.addFile(f);				
				refreshData();
				pHandler.sendEmptyMessage(1);
			}

			@Override
			public void onError(LiveOperationException exception,LiveOperation operation) {
				showToast(exception.getMessage());
				pHandler.sendEmptyMessage(1);
			}});		
	}
	
	
	private void shareFile(final String path){
		final ProgressDialog pd = ProgressDialog.show(this, "", FileListActivity.this.getString(R.string.msg_waite));
		String sp = path+"/shared_read_link";
		pHandler.sendEmptyMessage(0);
		pd.show();
		mClient.getAsync(sp, new LiveOperationListener(){
			@Override
			public void onComplete(LiveOperation operation) {
				pHandler.sendEmptyMessage(1);
				Intent sendIntent = new Intent();
				sendIntent.setAction(Intent.ACTION_SEND);
				sendIntent.putExtra(Intent.EXTRA_TEXT, operation.getResult().optString("link"));
				sendIntent.setType("text/plain");
				pd.dismiss();
				startActivity(sendIntent);
			}

			@Override
			public void onError(LiveOperationException exception,LiveOperation operation) {
				pHandler.sendEmptyMessage(1);
				pd.dismiss();
				showToast(exception.getMessage());
			}});
	}
	
	AlertDialog getAlertDialogNewFolder(final String path){
		final FrameLayout fl = new FrameLayout(FileListActivity.this);
		final EditText title = new EditText(FileListActivity.this);
		title.setSingleLine(false);
		title.setGravity(Gravity.TOP);
		
		fl.addView(title, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT, FrameLayout.LayoutParams.FILL_PARENT));
		
		AlertDialog.Builder builder = new AlertDialog.Builder(FileListActivity.this);
		builder.setView(fl).setTitle(res.getString(R.string.title_create_folder)).
			setPositiveButton(res.getString(R.string.ok), new DialogInterface.OnClickListener(){		    	 
                @Override
                public void onClick(DialogInterface d, int which) {  
                	String name = title.getText().toString();
                   	createFolder(path,name,"");    
                }
		    }).
		    setNegativeButton(res.getString(R.string.cancel), new DialogInterface.OnClickListener(){		    	 
                @Override
                public void onClick(DialogInterface d, int which) {
                	d.dismiss();
                }
		    });
		
		return builder.create();
	}
	
	
	AlertDialog getAlertDialogTextEdit(String title,String value,final String path){
		final FrameLayout fl = new FrameLayout(FileListActivity.this);
		final EditText input = new EditText(FileListActivity.this);
		input.setSingleLine(false);
		input.setGravity(Gravity.TOP);
		input.setText(value);
		fl.addView(input, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT, FrameLayout.LayoutParams.FILL_PARENT));
		
		AlertDialog.Builder builder = new AlertDialog.Builder(FileListActivity.this);
		builder.setView(fl).setTitle(title).
			setPositiveButton(res.getString(R.string.ok), new DialogInterface.OnClickListener(){		    	 
                @Override
                public void onClick(DialogInterface d, int which) {  
                	String name = input.getText().toString();
                	for(int i=0; i<files.size(); i++){
            			SkyDriveObject obj = files.get(i);
            			if(obj.getId().equals(path)){
            				files.get(i).setName(name);
            			}
            		}            		
            		initData();
            		

            		pHandler.sendEmptyMessage(0);
                	renameFile(path,name);
                }
		    }).
		    setNegativeButton(res.getString(R.string.cancel), new DialogInterface.OnClickListener(){		    	 
                @Override
                public void onClick(DialogInterface d, int which) {
                	d.dismiss();
                }
		    });
		
		return builder.create();
	}
	
	private String getFileModifyDate(String time){
		if(time==null || time.length()==0)
			return "";
		
		String date = time;
		String[] ss1 = time.split("\\+");
		if(ss1.length>1){
			String[] ss2 = ss1[0].split("T");
			if(ss2.length>1){
				date = ss2[0];
				
			}
		}
		
		return date;
	}
	
	public SkyDriveObject initObject(String json,String sDate){
		try{
			JSONObject skyDriveObject = new JSONObject(json);
			String type = skyDriveObject.optString("type");
			SkyDriveObject obj = null;
	        if (type.equals(SkyDriveFolder.TYPE)) {
	        	obj = new SkyDriveFolder(skyDriveObject);
	        } else if (type.equals(SkyDriveFile.TYPE)) {
	        	obj = new SkyDriveFile(skyDriveObject);
	        } else if (type.equals(SkyDriveAlbum.TYPE)) {
	        	obj = new SkyDriveAlbum(skyDriveObject);
	        } else if (type.equals(SkyDrivePhoto.TYPE)) {
	        	obj = new SkyDrivePhoto(skyDriveObject);
	        } else if (type.equals(SkyDriveVideo.TYPE)) {
	        	obj = new SkyDriveVideo(skyDriveObject);
	        } else if (type.equals(SkyDriveAudio.TYPE)) {
	        	obj = new SkyDriveAudio(skyDriveObject);
	        } else {
	        	obj = new SkyDriveFile(skyDriveObject);
	        }
	        
	        if(obj!=null){
	        	obj.setMeta(sDate);
	        	return obj;
	        }
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	private class LoadFolderTask extends AsyncTask<String, Integer, String> {
		@Override
		protected String doInBackground(String... params) {
			loadFolder();			
			return "All Done!";
		}
	}
	
	private void delConfirm(final String path){
		new AlertDialog.Builder(this)
				.setIcon(android.R.drawable.ic_dialog_alert)
				.setTitle(res.getString(R.string.title_delete))
				.setMessage(res.getString(R.string.msg_delete))
				.setPositiveButton(res.getString(R.string.ok), new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						removeFile(path);
					}

				}).setNegativeButton(res.getString(R.string.cancel), null).show();
	}
	
	private String[] getDownlods(){
		String director = Environment.getExternalStorageDirectory().getPath();
        File file = new File(director+"/SkyDrive");
        
        if(!file.exists())
        	return new String[]{};
        else
        	return file.list();
	}
	
	private boolean isDownload(String fname){
		boolean isDown = false;
		for(String name : downloadFiles){
			if(name.equalsIgnoreCase(fname)){
				isDown = true;
				break;
			}
		}
		return isDown;
	}
	
	private List<String[]> getImgUrls(){
		List<String[]> all = new ArrayList<String[]>();
		List<String> lst = new ArrayList<String>();
		List<String> plst = new ArrayList<String>();
		List<String> nlst = new ArrayList<String>();
		List<String> pnlst = new ArrayList<String>();
		for(SkyDriveObject obj : files){
			if(obj.getType().equals(SkyDrivePhoto.TYPE)){
				SkyDrivePhoto ph = (SkyDrivePhoto)obj;
				Image[] imgs = ph.getImages();
				for(Image img : imgs){
					if(img.getType().equalsIgnoreCase("thumbnail")){
						lst.add(img.getSource());
						plst.add(ph.getId());
						nlst.add(ph.getName());
					}
					
					if(img.getType().equalsIgnoreCase("normal")){
						pnlst.add(img.getSource());
					}
				}
			}
		}
		
		String[] imgs = new String[lst.size()];
		lst.toArray(imgs);
		all.add(imgs);
		String[] ids = new String[lst.size()];
		plst.toArray(ids);
		all.add(ids);
		String[] names = new String[lst.size()];
		nlst.toArray(names);
		all.add(names);
		String[] imgsNormal = new String[lst.size()];
		pnlst.toArray(imgsNormal);
		all.add(imgsNormal);
		
		return all;
	}
	
	private String getParentName(){
		String name = "SkyDrive";
		try{
			String parentId = "";
			for(SkyDriveObject obj : files){
				if(this.mCurrentFolderId.equalsIgnoreCase(obj.getId())){
					parentId = obj.getParentId();
					break;
				}
			}
			
			if(!parentId.equals(this.HOME_FOLDER)){
				name = fManager.getFile(parentId).getName();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return name;
	}
	
	private String getExtName(String name){
		String ext = "";
		if(name!=null && name.lastIndexOf(".")>=0){
			ext= name.substring(name.indexOf(".")+1);
		}
		return ext;
	}
	
	private int getExtIcon(String name){
		String ext = getExtName(name);
		int icon = -1;
		
		if("doc".equalsIgnoreCase(ext) || "docx".equalsIgnoreCase(ext)){
			icon = R.drawable.ic_doc;
		}else if("xls".equalsIgnoreCase(ext) || "xlsx".equalsIgnoreCase(ext)){
			icon = R.drawable.ic_excel;
		}else if("pps".equalsIgnoreCase(ext) || "ppsx".equalsIgnoreCase(ext)){
			icon = R.drawable.ic_pps;
		}else if("pdf".equalsIgnoreCase(ext)){
			icon = R.drawable.ic_pdf;
		}else if("zip".equalsIgnoreCase(ext)){
			icon = R.drawable.ic_zip;
		}else if("WAV".equalsIgnoreCase(ext) || 
				"MP3".equalsIgnoreCase(ext) || 
				"WMA".equalsIgnoreCase(ext) ||
				"MIDI".equalsIgnoreCase(ext) ||
				"RA".equalsIgnoreCase(ext) ||
				"RM".equalsIgnoreCase(ext) ||
				"VQF".equalsIgnoreCase(ext)){
			icon = R.drawable.ic_audio;
		}else if("AVI".equalsIgnoreCase(ext) || 
				"MOV".equalsIgnoreCase(ext) || 
				"ASF".equalsIgnoreCase(ext) ||
				"NAVI".equalsIgnoreCase(ext) ||
				"3GP".equalsIgnoreCase(ext) ||
				"MKV".equalsIgnoreCase(ext) ||
				"FLV".equalsIgnoreCase(ext) ||
				"RMVB".equalsIgnoreCase(ext) ||
				"F4V".equalsIgnoreCase(ext) ||
				"WebM".equalsIgnoreCase(ext) ){
			icon = R.drawable.ic_vedio;
		}
		
		return icon;
	}
	
	private void setFileIcon(View v,String name){
		int icon = getExtIcon(name);
		if(icon>0){
			v.setBackgroundResource(icon);
		}
	}
	
	private void filterFiles(List<SkyDriveObject> files, String filter){
		if(filter!=null && filter.trim().length()>0){
			List<SkyDriveObject> tmp = new ArrayList<SkyDriveObject>();
			for(SkyDriveObject obj : files){
				if(FILTER_PHOTOS.equalsIgnoreCase(filter)){
					if(obj.getType().equalsIgnoreCase(SkyDriveAlbum.TYPE) ||
						obj.getType().equalsIgnoreCase(SkyDrivePhoto.TYPE)){
						tmp.add(obj);
					}
				}else if (FILTER_DOCUMENT.equalsIgnoreCase(filter)){
					if(!obj.getType().equalsIgnoreCase(SkyDriveAlbum.TYPE) &&
						!obj.getType().equalsIgnoreCase(SkyDrivePhoto.TYPE)){
						tmp.add(obj);
					}
				} 			
			}
			
			files.clear();
			files.addAll(tmp);
		}
	}
	
	private class DataUpdateReceiver extends BroadcastReceiver {
	    @Override
	    public void onReceive(Context context, Intent intent) {
	    	String id = intent.getExtras().getString("id");
	    	int current = intent.getExtras().getInt("current");
	    	Message msg = proHandler.obtainMessage();
	    	Bundle data = new Bundle();
	    	data.putString("id", id);
	    	data.putInt("current", current);
	    	msg.setData(data);
	    	proHandler.sendMessage(msg);
	    }
	}
	
	private class SyncReceiver extends BroadcastReceiver {
	    @Override
	    public void onReceive(Context context, Intent intent) {
	    	String path = intent.getExtras().getString("parent");
	    	if(FileListActivity.this.mCurrentFolderId.equalsIgnoreCase(path)){
	    		String error = intent.getExtras().getString("error");
	    		if(error!=null){
	    			showToast(error);
	    		}else{
	    			handler.sendEmptyMessage(0);
	    		}
	    	}
	    }
	}
	
	class ImageDialog extends Dialog {
	    Context context;
	    SkyDrivePhoto photo;
	    File file;
	    
	    public ImageDialog(Context context) {
	        super(context);
	        this.context = context;
	    }
	    public ImageDialog(Context context, int theme,SkyDrivePhoto photo,File file){
	        super(context, theme);
	        this.context = context;
	        this.photo = photo;
	        this.file = file;
	    }
	    @Override
	    protected void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        this.setContentView(R.layout.image_dialog);

			TextView title = (TextView) this.findViewById(R.id.dialog_imag_title);
			title.setText(file.getName());
	        ImageView img = (ImageView) this.findViewById(R.id.dialog_imag);
			String src = photo.getSource();
			imageLoader.displayImage(src, img, dgOptions);
			img.setVisibility(View.VISIBLE);
			
			Button oButton = (Button) this.findViewById(R.id.dg_open);
			Button dButton = (Button) this.findViewById(R.id.dg_download);
			Button nButton = (Button) this.findViewById(R.id.dg_cancel);
			if(file.exists()){
				dButton.setVisibility(View.GONE);
				oButton.setOnClickListener(new View.OnClickListener(){
					@Override
					public void onClick(View v) {				        
						Intent intent = new Intent();
                        intent.setAction(android.content.Intent.ACTION_VIEW);                   
                        MimeTypeMap mime = MimeTypeMap.getSingleton();
                        String ext=FileUtil.getFileExt(file.getName());
                        if(ext!=null)
                        	ext = ext.toLowerCase();
                        String type = mime.getMimeTypeFromExtension(ext);                  
                        intent.setDataAndType(Uri.fromFile(file),type);                   
                        startActivity(intent);
                        ImageDialog.this.dismiss();
					}});
			}else{
				dButton.setVisibility(View.VISIBLE);
				oButton.setOnClickListener(new View.OnClickListener(){
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(FileListActivity.this, DownloadMessageService.class);
						String source = photo.getSource();
						intent.putExtra("source", source);
						intent.putExtra("name", file.getName());
						intent.putExtra("id", photo.getId());
						startService(intent);
						ImageDialog.this.dismiss();
					}});
			}
			
			dButton.setOnClickListener(new View.OnClickListener() {						
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(FileListActivity.this, DownloadService.class);
					intent.putExtra("operation", DownloadService.OP_DOWNLOAD);
					String source = photo.getSource();
					intent.putExtra("source", source);
					intent.putExtra("name", file.getName());
					startService(intent);
					showToast(res.getString(R.string.download_start));		
					ImageDialog.this.dismiss();
				}
			});
			
			nButton.setOnClickListener(new View.OnClickListener() {						
				@Override
				public void onClick(View v) {
					ImageDialog.this.dismiss();
				}
			});
	    }
	}
	
	private Handler proHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {   
        	try{
        		actionBar.setProgressBarVisibility(View.VISIBLE);
        		String id = msg.getData().getString("id");
            	String name = "";
            	int current = msg.getData().getInt("current");
            	int position = -1;
            	
            	for(int i=0; i<adapter.getCount(); i++){
            		SkyDriveObject obj = adapter.getItem(i);
            		if(obj.getId().equalsIgnoreCase(id)){
            			position = i;
            			name = obj.getName();
            			break;
            		}
            	}
            	
            	
            	if(position>=0){
            		int firstPosition = lsComposer.getFirstVisiblePosition() - lsComposer.getHeaderViewsCount();
            		int wantedChild = position - firstPosition;
            		if (wantedChild < 0 || wantedChild >= lsComposer.getChildCount()) {
            			return;
            		}
            		View itemView = lsComposer.getChildAt(wantedChild);
            		
            		//View itemView = plist.getRefreshableView().getChildAt(position+1);
            		//Log.e("DHH", itemView==null?"itemView is null":itemView.toString());
            		itemView.findViewById(R.id.fli_detail_lst).setVisibility(View.GONE);
            		ProgressBar bar = (ProgressBar) itemView.findViewById(R.id.fli_progress);
            		bar.setVisibility(View.VISIBLE);
            		bar.setMax(100);
            		bar.setProgress(current);
            		
            		if(current>=100){
            			bar.setVisibility(View.GONE);
            			itemView.findViewById(R.id.fli_detail_lst).setVisibility(View.VISIBLE);
            			itemView.findViewById(R.id.fli_downloaded).setVisibility(View.VISIBLE);
            			
            			String director = Environment.getExternalStorageDirectory().getPath();
            			File file = new File(director+"/SkyDrive/"+name);
            			
    					Intent intent = new Intent();
                        intent.setAction(android.content.Intent.ACTION_VIEW);                   
                        MimeTypeMap mime = MimeTypeMap.getSingleton();
                        String ext= FileUtil.getFileExt(file.getName());
                        if(ext!=null)
                        	ext = ext.toLowerCase();
                        String type = mime.getMimeTypeFromExtension(ext);                  
                        intent.setDataAndType(Uri.fromFile(file),type);                   
                        startActivity(intent);    
                        actionBar.setProgressBarVisibility(View.GONE);
            		}
            	}
        	}catch(Exception e){
        		actionBar.setProgressBarVisibility(View.GONE);
        		e.printStackTrace();
        	}
        	
        }
    };
}


